import React, { useState, useEffect, useRef } from 'react';
import { Input, Button, Space } from 'antd';
import './ContentDemo.less'

const SearchableContent = ({ content }) => {
    const [searchText, setSearchText] = useState('');
    const [highlightedContent, setHighlightedContent] = useState(content);
    const [matches, setMatches] = useState([]);
    const [currentMatchIndex, setCurrentMatchIndex] = useState(-1);
    const searchTimeoutRef = useRef(null); // 用于存储 timeout 的引用 ，用于输入防抖

    useEffect(() => {
        if (searchText === '') {
            setHighlightedContent(content);  // 重置原始高亮内容
            setMatches([]);
            setCurrentMatchIndex(-1);
            return;
        }
        // 清除之前的 timeout 以实现防抖  
        clearTimeout(searchTimeoutRef.current);

        // 设置新的 timeout  
        searchTimeoutRef.current = setTimeout(() => {
            const regex = new RegExp(`(${searchText})`, 'gi');
            const foundMatches = [];
            let match;

            while ((match = regex.exec(content)) !== null) {
                foundMatches.push(match.index);
            }

            setMatches(foundMatches);
            if (foundMatches.length > 0) {
                setCurrentMatchIndex(0);
                scrollToMatch(0);
            } else {
                setCurrentMatchIndex(-1);
            }
        }, 300); // 设置防抖的延迟时间为 300 毫秒  

        // 清理函数，以确保在组件卸载时清理 timeout  
        return () => clearTimeout(searchTimeoutRef.current);
    }, [searchText, content]);

    // 搜索
    const handleSearch = () => {
        const regex = new RegExp(`(${searchText})`, 'gi');
        const matches = [];
        let match;
        while ((match = regex.exec(content)) !== null) {
            matches.push(match.index);
        }

        setMatches(matches);

        if (matches.length > 0) {
            // 高亮匹配项  
            setCurrentMatchIndex(0);
            // 确保高亮后再滚动  
            setHighlighted(0); // 高亮第一个匹配项 
            setTimeout(() => {
                scrollToMatch(0);
            }, 500);
              
        } else {
            setCurrentMatchIndex(-1);
            setHighlightedContent(content); // 清除高亮内容  
        }
    };
    //设置定位到的高亮
    const setHighlighted = (index) => {
        const regex = new RegExp(`(${searchText})`, 'gi');
        const highlightedContent = content.replace(regex, (match, p1, offset) => {
            const isCurrentMatch = index !== -1 && index === matches.indexOf(offset);
            return `<mark class="${isCurrentMatch ? 'selected-highlight' : 'normal-highlight'}">${p1}</mark>`;
        });
        setHighlightedContent(highlightedContent);
    };
    //下一个
    const goToNextMatch = () => {
        if (matches.length > 0) {
            const nextIndex = (currentMatchIndex + 1) % matches.length;
            setCurrentMatchIndex(nextIndex);
            setHighlighted(nextIndex);
            scrollToMatch(nextIndex);
        }
    };
    //上一个
    const goToPreviousMatch = () => {
        if (matches.length > 0) {
            const prevIndex = (currentMatchIndex - 1 + matches.length) % matches.length;
            setCurrentMatchIndex(prevIndex);
            setHighlighted(prevIndex);
            scrollToMatch(prevIndex);
        }
    };
    //滚动到标记位置
    const scrollToMatch = (index) => {
        const markElements = document.querySelectorAll('mark');
        if (markElements[index]) {
            markElements[index].scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    };


    return (
        <div className="searchable-content">
            <div className="sticky-search-bar">
                <Input
                    placeholder="输入关键词搜索"
                    value={searchText}
                    autoFocus
                    onChange={(e) => setSearchText(e.target.value)}
                    style={{ marginRight: 8, width: 300 }}
                    suffix={matches.length > 0 ? <span>{currentMatchIndex + 1}/{matches.length}</span> : ''}
                />
                <Space>
                    <Button type="primary" onClick={handleSearch}>搜索</Button>
                    <Button onClick={goToPreviousMatch} disabled={currentMatchIndex === -1}>上一个</Button>
                    <Button onClick={goToNextMatch} disabled={currentMatchIndex === -1}>下一个</Button>
                </Space>
            </div>
            <div
                className="highlighted-content"
                dangerouslySetInnerHTML={{ __html: highlightedContent }}
            />
        </div>
    );
};

export default SearchableContent;